package com.krain.ddbb.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.krain.ddbb.R;
import com.krain.ddbb.base.BaseActivity;
import com.krain.ddbb.constant.Keys;
import com.krain.corelibrary.helper.ImageHelper;
import com.krain.corelibrary.helper.imageloader.depend.Utils;
import com.krain.corelibrary.util.FileUtil;
import com.orhanobut.logger.Logger;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.UiThread.Propagation;
import org.androidannotations.annotations.ViewById;
import org.apache.http.client.ClientProtocolException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 拍照选取照片
 * 
 * @author dale.liu
 * 
 */
@EActivity(R.layout.activity_take_pic_by_cameral)
public class TakePicByCameralActivity extends BaseActivity {

    private Camera            m_camera;
    private SurfaceHolder     m_surface_holder;

    private boolean           m_flag_support_af = false;
    private boolean           m_flag_in_af      = false;
    private boolean           m_flag_will_take  = false;
    private Bitmap            bMapRotate;

    private ArrayList<String> filePaths         = new ArrayList<String>();

    @ViewById(R.id.take_pic_surface)
    SurfaceView               mCameralView;
    @ViewById(R.id.take_pic_camera_take)
    View                      mShutter;
    @ViewById(R.id.back_tv)
    TextView                  mTvBack;

    @Override
    protected String getToolbarTitle() {
        return null;
    }

    @SuppressWarnings("deprecation")
    @AfterViews
    void init() {
      //  SoundManager.getSingleton().preload(this);
        mCameralView.setVisibility(View.VISIBLE);
        mShutter.setVisibility(View.GONE);
        m_surface_holder = mCameralView.getHolder();
        m_surface_holder.addCallback(mSurfaceHolderCallback);
        m_surface_holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mCameralView.setOnClickListener(mListenerClick);
        mShutter.setOnClickListener(mListenerClick);
      //  IconfontUtil.setIcon(this, mTvBack, AnanzuIcon.TEST);
        mTvBack.setBackgroundResource(R.mipmap.code_icon);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onBackPressed() {
        back();
    }

    @Click(R.id.back_tv)
    void back() {
        deleteFileTake();
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }

    private void deleteFileTake() {
        if (filePaths != null && filePaths.size() > 0) {
            FileUtil.deleteFiles(filePaths);
        }
    }

    @Click(R.id.complete)
    void complete() {
        if (filePaths != null && filePaths.size() > 0) {
            Intent data = new Intent();
            data.putStringArrayListExtra(Keys.FILE_PATH_KEY, filePaths);
            setResult(RESULT_OK, data);
            finish();
        } else {
            back();
        }
    }

    @Override
    protected void onDestroy() {
        if (bMapRotate != null && !bMapRotate.isRecycled()) {
            bMapRotate.recycle();
        }
        super.onDestroy();
    }

    /**
     * 初始化相机
     */
    private void initCamera() {
        try {
            mShutter.setVisibility(View.VISIBLE);
            mShutter.setEnabled(false);
            if (null == m_camera) {
//                showLoadingProgress(R.string.take_photo_init, "");
                openCameral();
            }

        } catch (Exception e) {
            if (null != m_camera) {
                m_camera.stopPreview();
                m_camera.release();
                m_camera = null;
            }
        }
    }

    @UiThread(propagation = Propagation.REUSE)
    void setCameralPara() {
        if (null == m_camera) {// 不支持摄像头
            // showTipMsg(getString(R.string.no_camera));
            mShutter.setVisibility(View.GONE);
        } else {
            m_flag_support_af = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_AUTOFOCUS);
            Camera.Parameters params = m_camera.getParameters();
            setPreviewSize(params);
            m_camera.setParameters(params);

            try {
                m_camera.setPreviewDisplay(m_surface_holder);
            } catch (IOException e) {
                e.printStackTrace();
            }

            m_camera.startPreview();

            if (m_flag_support_af && !m_flag_in_af) {// 首次自动对焦，提升用户体验
                m_flag_in_af = true;
                m_camera.autoFocus(mCallbackAf);
            }

            if (m_flag_support_af) {
                // 相机不支持聚焦
            } else {
                mShutter.setVisibility(View.GONE);
            }
        }
        mShutter.setEnabled(true);
//        closeLoadingProgress();
    }

    @Background(id = "openCameral")
    void openCameral() {
        m_camera = Camera.open();
        m_camera.setDisplayOrientation(90);
        setCameralPara();
    }

    /**
     * 释放相机
     */
    private void releaseCamera() {
        if (null != m_camera) {
            m_camera.stopPreview();
            m_camera.release();
            m_camera = null;
        }
    }

    /**
     * 设置预览的大小，拍摄照片的大小
     * 
     * @param params
     *            相机参数对象
     */
    private void setPreviewSize(Camera.Parameters params) {
        Size avaliable = null;
        int surface = mCameralView.getWidth() * mCameralView.getHeight();

        List<Size> surpport = params.getSupportedPreviewSizes();
        Collections.sort(surpport, m_comparator);

        for (Size size : surpport) {
            if (surface <= size.width * size.height) {
                avaliable = size;
                break;
            }
        }

        if (null == avaliable) {
            avaliable = surpport.get(surpport.size() - 1);
        }

        params.setPreviewSize(avaliable.width, avaliable.height);

        avaliable = null;
        surpport = params.getSupportedPictureSizes();
        Collections.sort(surpport, m_comparator);

        for (Size size : surpport) {
            if (surface <= size.width * size.height) {
                avaliable = size;
                break;
            }
        }

        if (null == avaliable) {
            avaliable = surpport.get(surpport.size() - 1);
        }

        params.setPictureSize(avaliable.width, avaliable.height);
    }

    /**
     * 拍摄照片
     */
    private void takePicture() {
        if (null != m_camera) {
            if (m_flag_support_af) {
                if (m_flag_in_af) {
                    m_flag_will_take = true;
                } else {
                    m_flag_will_take = true;
                    m_flag_in_af = true;
                    m_camera.autoFocus(mCallbackAf);
                }
            } else {
                m_camera.takePicture(null, null, mCallbackPicture);
            }
        }
    }

    // @formatter:off
    private SurfaceHolder.Callback mSurfaceHolderCallback = new SurfaceHolder.Callback() {

          @Override
          public void surfaceDestroyed(SurfaceHolder holder) {
              releaseCamera();
          }

          @Override
          public void surfaceCreated(SurfaceHolder holder) {
          }

          @Override
          public void surfaceChanged(SurfaceHolder holder,
                  int format, int width, int height) {
              initCamera();
          }
      };

    /**
     * 拍摄照片
     */
    private Camera.PictureCallback mCallbackPicture       = new Camera.PictureCallback() {

                                                              @Override
                                                              public void onPictureTaken(byte[] data, Camera camera) {
                                                                  try {
                                                                    //  SoundManager.getSingleton().play(
                                                                        //      SoundManager.SOUND_SHUTTER);
                                                                      int orientation = 0;
                                                                      BitmapFactory.Options options = new BitmapFactory.Options();
                                                                      Bitmap bMap;
                                                                      bMap = BitmapFactory.decodeByteArray(data, 0,
                                                                              data.length, options);
                                                                      if (bMap.getHeight() < bMap.getWidth()) {
                                                                          orientation = 90;
                                                                      } else {
                                                                          orientation = 0;
                                                                      }
                                                                      if (orientation != 0) {
                                                                          Matrix matrix = new Matrix();
                                                                          matrix.postRotate(orientation);
                                                                          bMapRotate = Bitmap.createBitmap(bMap, 0, 0,
                                                                                  bMap.getWidth(), bMap.getHeight(),
                                                                                  matrix, true);
                                                                      } else {
                                                                          bMapRotate = Bitmap.createScaledBitmap(bMap,
                                                                                  bMap.getWidth(), bMap.getHeight(),
                                                                                  true);
                                                                      }
                                                                      mShutter.setEnabled(true);
                                                                      saveBitMap(bMap);

                                                                      m_flag_in_af = false;
                                                                      m_flag_will_take = false;
                                                                      if (null != m_camera && m_flag_support_af
                                                                              && !m_flag_in_af) {
                                                                          m_flag_in_af = true;
                                                                          m_camera.startPreview();
                                                                          m_camera.autoFocus(mCallbackAf);
                                                                      }
                                                                  } catch (Exception e) {
                                                                      e.printStackTrace();
                                                                  }
                                                              }
                                                          };

    private View.OnClickListener   mListenerClick         = new View.OnClickListener() {
                                                              @Override
                                                              public void onClick(View v) {
                                                                  switch (v.getId()) {
                                                                  case R.id.take_pic_surface:
                                                                      if (null != m_camera && m_flag_support_af
                                                                              && !m_flag_in_af) {
                                                                          m_flag_in_af = true;
                                                                          m_camera.autoFocus(mCallbackAf);
                                                                      }
                                                                      break;
                                                                  case R.id.take_pic_camera_take:
                                                                      mShutter.setEnabled(false);
                                                                      takePicture();
                                                                      break;
                                                                  }
                                                              }
                                                          };

    // @formatter:on
    @Background(id = "savebitMap")
    void saveBitMap(Bitmap bmp) {
        try {
            String pathSaveParent = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                    .getAbsolutePath();
            File fileSave = FileUtil.saveBitmap(this, bMapRotate, pathSaveParent, System.nanoTime() + "");
            if (fileSave.exists()) {
                ImageHelper imageHelper = ImageHelper.getInstance(this);
                try {
                    String cachePath = saveCompressBitmap(bMapRotate, fileSave.getAbsolutePath(), imageHelper);
                    filePaths.add(cachePath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                baseUtil.showSnackBar(this, "已经添加" + filePaths.size() + "张");
                if (bmp != null) {
                    bmp.recycle();
                }
            }
        } catch (Exception e) {
            baseUtil.showSnackBar(this, "当前系统相册路径不可用,添加失败");
        }
    }

    private String saveCompressBitmap(Bitmap bitmap, String path, ImageHelper imageHelper)
            throws ClientProtocolException, IOException, FileNotFoundException {
        imageHelper.loadImage(path, MultipleAlbumActivity.DEFAULT_WIDTH, MultipleAlbumActivity.DEFAULT_HEIGHT);
        String parentPath = TakePicByCameralActivity.getImageCheDir(this);
        String pathCache = parentPath + System.nanoTime() + ".jpg";
        File fileCache = new File(pathCache);
        File pf = fileCache.getParentFile();
        if (pf != null) {
            pf.mkdirs();
        }
        if (!fileCache.exists()) {
            fileCache.createNewFile();
        }
        // imageHelper.writeToFile(bitmap, CompressFormat.JPEG, fileCache);
        imageHelper.writeToFile(bitmap, CompressFormat.JPEG, MultipleAlbumActivity.COMPRESS_QAUILTY, fileCache);
        return pathCache;
    }




    //@formatter:off    
    private AutoFocusCallback mCallbackAf  = new AutoFocusCallback() {
           @Override
           public void onAutoFocus(boolean success, Camera camera) {
               if (m_flag_will_take) {
                   m_camera.takePicture(null, null, mCallbackPicture);
               } else {
                   m_flag_in_af = false;
               }
           }
       };

    private Comparator<Size>  m_comparator = new Comparator<Size>() {
           @Override
           public int compare(Size lhs, Size rhs) {
               return lhs.width * lhs.height - rhs.width * rhs.height;
           }
    
       };

    // @formatter:on
    public static String getImageCheDir(Context ctx) {
        String filePath = Utils.getCacheDir(ctx);
        return filePath = filePath + File.separator + "img" + File.separator;
    }

    /** 删除压缩的图pain */
    public static void deleteCompressImgs(Context ctx) {
        Logger.v("zj", "--> deleteCompressImgs()");
        final String dirPath = getImageCheDir(ctx);
        new Thread(new Runnable() {

            @Override
            public void run() {
                if (TextUtils.isEmpty(dirPath)) {
                    return;
                }
                try {
                    File dirFile = new File(dirPath);
                    File[] imgs = dirFile.listFiles();
                    for (File img : imgs) {
                        img.delete();
                    }
                } catch (Exception e) {
                }
            }
        }).start();
    }
}
